import 'dart:math';

import 'package:flutter/material.dart';

class Settings extends StatefulWidget {
  const Settings({super.key});

  @override
  State createState() => SettingsState();
}

class SettingsState extends State<Settings> {

  double _left = 0;
  double _top = 0;

  double tWidth = 0;
  double tHeight = 0;

  //全局key
  GlobalKey globalKey = GlobalKey();

  @override
  void initState() {

    super.initState();

    //注册一个回调   当屏幕首次渲染第一帧的时候回调
    WidgetsBinding.instance.addPostFrameCallback((_) {

      if (globalKey.currentContext?.size?.width != null) {
        tWidth = globalKey.currentContext!.size!.width;
      }

      if (globalKey.currentContext?.size?.height != null) {
        tHeight = globalKey.currentContext!.size!.height;
      }

      print("tWidth:$tWidth,tHeight:$tHeight");
    });


  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: globalKey,
        body: GestureDetector(
          onPanUpdate: (details) {
            setState(() {
              _left += details.delta.dx;
              _top += details.delta.dy;
              _left = max(0, min(_left, tWidth - 200));
              _top = max(0, min(_top, tHeight - 200));
            });
            print("_left:$_left,_top:$_top");
          },
          child: Stack(
            children: [
              Positioned(
                left: _left,
                top: _top,
                width: 200,
                height: 200,
                child: Container(color: Colors.redAccent,)
            )
          ],),
        )
    );
  }
}
